using System.Buffers;
using System.Net.Security;
using System.Text;
using eLibrary.Constant;
using eLibrary;
using ePipe;
using eTask.Extensions;
using Letter.IO.Binary;
using Letter.Net.SSL;
using Letter.Net.Tcp;

namespace tcp_server_test1;

public class STcpConnection : ADefaultFixedHeaderBytesConnection
{
    public STcpConnection() : base(BinaryOrder.BigEndian)
    {
        // Console.WriteLine("TcpConnection========================>" + this.Id);
    }

    public STcpConnection(BinaryOrder order) : base(order)
    {
    }

    public STcpConnection(BinaryOrder order, SSLOptions sslOptions, Func<Stream, SslStream> sslStreamFactory) : base(order, sslOptions, sslStreamFactory)
    {
    }

    private long isConnected = Booleans.FALSE;
    private string playerId;
    // private ITcpGatewayObserver observerAgent;
    // public TcpGatewayObserver tcpGatewayObserver;
    public IDuplexPipe<byte> Pipes
    {
        get { return base.Transport; }
    }


    private bool IsConnected
    {
        get { return Interlocked.Read(ref this.isConnected) == Booleans.TRUE; }
    }

    public override void OnActive()
    {
        base.OnActive();
        Console.WriteLine("OnActive===================================>");

        try
        {
            // TcpGatewayEnvironment.Increment();

            // var timerTask = (ITimerTask)this;
            // TimerRunner.CreateTimeout(timerTask, TimeSpan.FromSeconds(5));
            
        }
        catch (Exception ex)
        {
            Console.WriteLine("TCP断开连接============================>" + ex.Message);
        }
     
    }
  
    protected override void OnRcvBuffer(IPipeReader<byte> input, ref ReadOnlySequence<byte> buf)
    {
        Console.WriteLine("OnRcvBuffer===================================>");

        base.OnRcvBuffer(input, ref buf);
    }
    protected override void OnMessage(ReadOnlySequence<byte> buf)
    {
        // Console.WriteLine("OnMessage===================================>");
        //
        // var reader = buf.ToBytesReader();
        // var pak = new NetCommandPack();
        // pak.commandId = reader.ReadUInt16BE();
        // pak.protocolId = reader.ReadUInt16BE();
        // pak.flag = reader.ReadUInt8();
        // pak.data = reader.ReadBuffer((int)reader.ReadableLength).ToArray();
        //
        // this.MessageRoute(pak);
    }
    // private void MessageRoute(NetCommandPack pack)
    // {
    //
    //     Console.WriteLine("MessageRoute========================>" + this.Id);
    //
    //
    //     var command = (UC_COMMAND)pack.commandId;
    //
    //     if (this.IsConnected == true)
    //     {
    //         this.CloseAsync().Sync();
    //         return;
    //     }
    //
    //     switch (command)
    //     {
    //         case UC_COMMAND.LOGIN:
    //
    //             RcvLoginMessage(pack);
    //             break;
    //         case UC_COMMAND.PROJECT:
    //             RcvProjectMessage(pack);
    //             break;
    //         case UC_COMMAND.TRANSFROM:
    //             RcvTransformMessage(pack);
    //             break;
    //     }
    // }

    // private async void RcvTransformMessage(NetCommandPack pack)
    // {
    //     var sender = await Program.runtime.GetMessagerAsync<ISyllogeMessager>(ConstEntityName.SPACE_SYLLOGE_MANAGEMENT_ENTITY);
    //     await sender.Route(pack, playerId);
    // }
    //
    // private async void RcvLoginMessage(NetCommandPack pack)
    // {
    //     Console.WriteLine("RcvLoginMessage===================================>");
    //
    //     if (pack.protocolId == (byte)LoginProtocol.UC2S_ACCOUNT)
    //     {
    //         var str = Encoding.UTF8.GetString(pack.data);
    //         Console.WriteLine(str);
    //
    //         var data = Json.DeserializeObject<LoginProtocol_AccountPack>(str);
    //         try
    //         {
    //             var sender = await Program.runtime.GetMessagerAsync<IWorkLoginMessager>(ConstEntityName.WORK_LOGIN_TOKEN_ENTITY);
    //             this.playerId = await sender.RequestConnect(data.usernameMD5, data.passwordMD5, data.token);
    //             Console.WriteLine($"生成playerId！---------------------------{playerId}");
    //
    //         }
    //         catch (Exception e)
    //         {
    //             Console.WriteLine("登录网关失败1！-------------------------<<<<<" + e.Message);
    //             Console.WriteLine(e.StackTrace);
    //
    //             //登入失败
    //             await this.CloseAsync();
    //             return;
    //         }
    //         if (!string.IsNullOrEmpty(playerId))
    //         {
    //
    //             //登入成功
    //             Interlocked.Exchange(ref this.isConnected, Booleans.TRUE);
    //             try
    //             {
    //                 tcpGatewayObserver = new TcpGatewayObserver(this);
    //                 this.observerAgent = await Program.runtime.CreateObserverRefAsync<ITcpGatewayObserver>(tcpGatewayObserver);
    //                 var playerSender = await Program.runtime.GetMessagerAsync<IWorkPlayerMessager>(playerId);
    //                 await playerSender.Enter(observerAgent);
    //                 var sender = await Program.runtime.GetMessagerAsync<ISyllogeMessager>(ConstEntityName.SPACE_SYLLOGE_MANAGEMENT_ENTITY);
    //                 await sender.Enter(observerAgent);
    //
    //                 Console.WriteLine("登录网关成功！-------------------------<<<<<");
    //
    //             }
    //             catch (Exception e)
    //             {
    //                 Console.WriteLine("登录网关失败2！-------------------------<<<<<"+e.Message);
    //                 Console.WriteLine(e.StackTrace);
    //
    //                 //登入失败
    //                 await this.CloseAsync();
    //                 return;
    //             }
    //         }
    //         else
    //         {
    //             Console.WriteLine("登录网关失败3！-------------------------<<<<<");
    //
    //             //登入失败
    //             await this.CloseAsync();
    //         }
    //     }
    //     else if (pack.protocolId == (byte)LoginProtocol.UC2S_TOKEN)
    //     {
    //         
    //     }
    // }

    // private async void RcvProjectMessage(NetCommandPack pack)
    // {
    //     var messager = await Program.runtime.GetMessagerAsync<IWorkProjectMessager>(playerId);
    //     await messager.Route(pack);
    // }


    public override void OnException(Exception ex)
    {
        base.OnException(ex);
        Console.WriteLine("OnException>>>>>>>>>>" + ex.Message);
    }

    public override async void OnInactive()
    {
        Console.WriteLine("OnInactive===================================>");

        // TcpGatewayEnvironment.Decrement();
        // var playerSender = await Program.runtime.GetMessagerAsync<IWorkPlayerMessager>(playerId);
        // await playerSender.Exit();
        // var sender = await Program.runtime.GetMessagerAsync<ISyllogeMessager>(ConstEntityName.SPACE_SYLLOGE_MANAGEMENT_ENTITY);
        // await sender.Exit();
    }
}